package UDPEcho;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoCline {
    private DatagramSocket socket = null;
    //客户端的IP
    private String severIp;
    //客户端端口号
    private int severPort;

    public UDPEchoCline(String severIp,int severPort) throws SocketException {
        this.severIp = severIp;
        this.severPort = severPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.print("->");
            //1、从控制台读取要发送请求的数据
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //2、构造请求并发送
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(severIp),severPort);
            socket.send(requestPacket);
            //3、读取服务器响应
            DatagramPacket responesePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responesePacket);
            //4、把响应打印到控制台上
            String response = new String(responesePacket.getData(),0,responesePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoCline udpEchoCline = new UDPEchoCline("127.0.0.1",9090);
        udpEchoCline.start();
    }
}
